package maa.action.admin.mentor;

import maa.action.Action;
import maa.action.ActionResult;
import maa.dao.DAOCommand;
import maa.dao.DAOFactory;
import maa.dao.DAOManager;
import maa.database.ConnectionPool;
import maa.action.ActionException;
import maa.dao.DAOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.UUID;

public class AppointMentor implements Action {
    @Override
    public ActionResult execute(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        HttpSession session = req.getSession();
        ActionResult actionResult = new ActionResult();
        ConnectionPool connectionPool = ConnectionPool.getInstance();
        DAOManager daoManager = DAOFactory.createDAOManager(connectionPool.getConnection());
        String str = (String) session.getAttribute("course-uuid");
        final UUID course_uuid = UUID.fromString(str);
        String s = req.getParameter("mentor-uuid").substring(0, req.getParameter("mentor-uuid").length() - 1);
        final UUID mentor_uuid = UUID.fromString(s);
        DAOCommand command = new DAOCommand() {
            @Override
            public Object execute(DAOManager daoManager) throws ActionException {
                try {
                    return daoManager.getCourseDAO().setMentor(course_uuid, mentor_uuid);
                } catch (DAOException e) {
                    throw new ActionException("Exception in courseDAO.setMentor(course_uuid, mentor_uuid)");
                }
            }
        };
        Boolean flag = (Boolean) daoManager.executeAndClose(command);
        if (flag) {
            actionResult.setResult("success");
            actionResult.setRedirected(true);
            session.removeAttribute("course-uuid");
        }
        else {
            actionResult.setResult("admin-cabinet");
            actionResult.setRedirected(true);
        }
        return actionResult;
    }
}
